//
//  MainViewController.m
//  weappios
//
//  Created by chensentao on 2018/8/3.
//  Copyright © 2018年 XiGuangLu. All rights reserved.
//

#import "MainViewController.h"
#import <WebKit/WebKit.h>
#import "UIView+Activity.h"
#import "StringUtil.h"
#import "ApiClient.h"
#import "NSMutableDictionary+AllType.h"
#import "ViewUtils.h"
#import "AppContext.h"
#import "WXApi.h"
#import "UIImageHelper.h"
#import "ShareHelper.h"
#import "CalendarReminderUtil.h"
#import "Constants.h"
#import "AppDelegate.h"
#import "TTButton.h"
#import "AppConfig.h"
#import <WindSDK/WindSDK.h>
#import <BUAdSDK/BUAdSDK.h>
#import "JKEncrypt.h"

/////////为了防止内存泄漏
@interface WeakScriptMessageDelegate : NSObject<WKScriptMessageHandler>

@property (nonatomic, assign) id<WKScriptMessageHandler> scriptDelegate;

- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate;

@end

@implementation WeakScriptMessageDelegate

- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate
{
    self = [super init];
    if (self) {
        _scriptDelegate = scriptDelegate;
    }
    return self;
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    [self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
}
@end
////////////////////////////

@interface MainViewController ()<WKNavigationDelegate,WKScriptMessageHandler,WKUIDelegate,BURewardedVideoAdDelegate,WindRewardedVideoAdDelegate>

@property(nonatomic,strong)WKWebView *webView;
    
@property (nonatomic, strong) TTButton *shareButton;

@property (nonatomic, strong) BURewardedVideoAd *rewardedVideoAd;

@property (nonatomic, strong) NSString *urlScheme;

@end

@implementation MainViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view, typically from a nib.
//    self.edgesForExtendedLayout = UIRectEdgeNone;
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = [WKUserContentController new];
//    WKPreferences *preferences = [WKPreferences new];
//    preferences.javaScriptCanOpenWindowsAutomatically = YES;
//    preferences.minimumFontSize = 10.0;
//    configuration.preferences = preferences;
    self.webView=[[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) configuration:configuration];
    self.webView.navigationDelegate=self;
    self.webView.UIDelegate = self;
    [self.view addSubview:self.webView];
    
    [self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        //获取默认userAgent
        NSString *oldUA = result; //直接获取为nil
        [AppContext sharedContext].userAgent = oldUA;
        //设置userAgent：添加额外的信息
        NSString *newUA = [NSString stringWithFormat:@"%@ wkd_ua /%@ Tiantian Ling Qian Bao Wuhan LiuPeng %@", oldUA , [AppContext sharedContext].curChannel,[AppContext sharedContext].versionCode];
        NSLog(@"---oldUA:%@---newUA:%@", oldUA,newUA);
        //设置全局
//        NSDictionary *dictNU = [NSDictionary dictionaryWithObjectsAndKeys:newUA, @"UserAgent", nil];
//        [[NSUserDefaults standardUserDefaults] registerDefaults:dictNU];
        //设置局部
        [self.webView setCustomUserAgent:newUA];
    }];
    
    //添加js 调用方法
    WeakScriptMessageDelegate* delegate=[[WeakScriptMessageDelegate alloc] initWithDelegate:self];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"send_code"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"check_code"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"play"];//
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"jumpReward"];//
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"pauth"];//
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"saveUid"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"showDialog"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"shareToWx"];//
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"copy"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"savePic"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"shareInvite"];//
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"isInstalled"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"setReminder"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"jump"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"jumpAuth"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"awaken"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"share"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"checkInstall"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"update"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"pay"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"imei"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"yyz"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"showShare"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"yyzplay"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"loadTTAd"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"playTTAd"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"loadSigmobAd"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"playSigmobAd"];
    /******************************************************/
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"ttlqb_getClient_no"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"ttlqb_getLoadUserInfo"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"ttlqb_getOnlineStatus"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"ttlqb_getBreakStatus"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"ttlqb_pasteAction"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"ttlqb_getReInstallStatus"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"ttlqb_openApp"];
    [[_webView configuration].userContentController addScriptMessageHandler:delegate name:@"ttlqb_getInstallStatus"];
    
    NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:URL_WEB]];
    [self.webView loadRequest:request];
    
    [[ApiClient sharedApi] getSchemescb:^(NSDictionary *data, NSError *connectionError) {
        if (!connectionError) {
            self.urlScheme = data[@"schemes"];
        }
    }];
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSDictionary* body=message.body;
    NSLog(@"--------------%@：%@------------", message.name,body);
    
    //找到对应js端的方法名,获取messge.body
    if ([message.name isEqualToString:@"send_code"]) {
        NSMutableDictionary* dict=[NSMutableDictionary dictionary];
        [dict putStr:[body getStr:@"phone"] key:@"phone"];
        [[ApiClient sharedApi] send_code:dict cb:^(NSDictionary *data, NSError *connectionError) {
            if(data){
                int r=[data getInt:@"r"];
                NSString* msg=[data getStr:@"errmsg"];
                if(r==0||r==-1){
                    [ViewUtils showToast:msg];
                }
            }
        }];
        
    }else if([message.name isEqualToString:@"check_code"]){
        NSMutableDictionary* dict=[NSMutableDictionary dictionary];
        [dict putStr:[body getStr:@"phone"] key:@"phone"];
        [dict putStr:[body getStr:@"code"] key:@"code"];
        [dict putStr:[AppContext sharedContext].curChannel key:@"channel"];
        [[ApiClient sharedApi] check_code:dict cb:^(NSDictionary *data, NSError *connectionError) {
            if(data){
                int r=[data getInt:@"r"];
                NSString* msg=[data getStr:@"errmsg"];
                if(r==0){
                   NSString* uid=[data getStr:@"uid"];
                   [[AppContext sharedContext] setCurUid:uid];
                   [ViewUtils showToast:msg];
                }else if(r==-1){
                   [ViewUtils showToast:msg];
                }
            }
        }];
    }else if([message.name isEqualToString:@"play"]){
        if(![WXApi isWXAppInstalled]){
            [ViewUtils showToast:@"还没有安装微信哦～"];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:weixin]];
            return;
        }
        [WXApi registerApp:APP_ID];
        [self showDialog:@"正在跳转中..."];
        NSString* uid=[AppContext sharedContext].curUid;
        NSMutableDictionary* dict=[NSMutableDictionary dictionary];
        [dict putStr:uid key:@"uid"];
        [dict putStr:[body getStr:@"weappid"] key:@"weappid"];
        
        __weak __typeof(self)weakSelf=self;
        [[ApiClient sharedApi] play:dict cb:^(NSDictionary *data, NSError *connectionError) {
            [weakSelf dismissDialog];
            if(data){
                int r=[data getInt:@"r"];
                if(r==0){
                    NSDictionary* dictResult=[data getDict:@"result"];
                    NSString* ghid=[dictResult getStr:@"ghid"];
                    NSString* path=[dictResult getStr:@"path"];
                    int status=[dictResult getInt:@"status"];
                    //NSArray* j_pls_key=[dict getArray:@"pls_key"];
                    NSString* pls=[NSString stringWithFormat:@"%lld",[StringUtil curTimeMis]];
                    if(pls){
                        if([path rangeOfString:@"?"].location!=NSNotFound){
                            //如果有问号
                            path=[NSString stringWithFormat:@"%@&pls=%@",path,pls];
                        }else{
                            path=[NSString stringWithFormat:@"%@?pls=%@",path,pls];
                        }
                    }
                    WXLaunchMiniProgramReq *req = [WXLaunchMiniProgramReq object];
                    req.userName = ghid;  //拉起的小程序的username 其实就是
                    req.path = path;    //拉起小程序页面的可带参路径，不填默认拉起小程序首页
                    if(status==1){
                        //正式版小程序
                        req.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
                    }else{
                        //体验版小程序
                        req.miniProgramType = WXMiniProgramTypePreview;
                    }
                    [WXApi sendReq:req];
                    
                }else if(r==-1){
                    
                }
            }
        }];
    }else if([message.name isEqualToString:@"jumpReward"]){
        if(![WXApi isWXAppInstalled]){
            [ViewUtils showToast:@"还没有安装微信哦～"];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:weixin]];
            return;
        }
        [WXApi registerApp:APP_ID];
        [self showDialog:@"正在跳转中..."];
        NSString* uid=[AppContext sharedContext].curUid;
        NSMutableDictionary* dict=[NSMutableDictionary dictionary];
        [dict putStr:uid key:@"uid"];
        __weak __typeof(self)weakSelf=self;
        [[ApiClient sharedApi] jump_reward:dict cb:^(NSDictionary *data, NSError *connectionError) {
            [weakSelf dismissDialog];
            if(data){
                int r=[data getInt:@"r"];
                if(r==0){
                    NSDictionary* dictResult=[data getDict:@"result"];
                    NSString* ghid=[dictResult getStr:@"ghid"];
                    NSString* path=[dictResult getStr:@"path"];
                    int status=[dictResult getInt:@"status"];
                    
                    WXLaunchMiniProgramReq *req = [WXLaunchMiniProgramReq object];
                    req.userName = ghid;  //拉起的小程序的username 其实就是
                    req.path = path;    //拉起小程序页面的可带参路径，不填默认拉起小程序首页
                    if(status==1){
                        //正式版小程序
                        req.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
                    }else{
                        //体验版小程序
                        req.miniProgramType = WXMiniProgramTypePreview;
                    }
                    [WXApi sendReq:req];
                    
                }else if(r==-1){
                    
                }
            }
        }];
    }else if([message.name isEqualToString:@"pauth"]){
        //这个还未实现
        
    }else if([message.name isEqualToString:@"saveUid"]){
        [[AppContext sharedContext] setCurUid:[body getStr:@"uid"]];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"uid"] = [AppContext sharedContext].curUid;
        dict[@"cid"] = [AppContext sharedContext].clientId;
        [[ApiClient sharedApi] getui_cid:dict cd:^(NSDictionary *data, NSError *connectionError) {
            NSLog(@"data2:%@",data);
        }];
    }else if([message.name isEqualToString:@"showDialog"]){
        //展示框
        [self showDialog:[body getStr:@"wn"]];
    }else if([message.name isEqualToString:@"shareToWx"]){
        if(![WXApi isWXAppInstalled]){
            [ViewUtils showToast:@"还没有安装微信哦～"];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:weixin]];
            return;
        }
        [WXApi registerApp:APP_ID];
        [self dismissDialog];
        //分享到微信
        int intFlag=[body getInt:@"flag"];
        if(intFlag==1){
            NSString* str=[body getStr:@"haibao"];
            NSArray* list=[self arrayWithJsonString:str];
            if(list){
                if(list.count>1){
                    [ShareHelper shareImgs:intFlag imgs:list txt:nil type:@"wchat" vc:self okfunc:^{
                        //分享完成
                    }];
                }else{
                    NSArray* imgs=[NSArray arrayWithObject:list[0]];
                    [UIImageHelper downloadDataThenUpdateUI:imgs complete:^(NSArray *datas) {
                        if(datas&&datas.count>0){
                            NSData* data=datas[0];
                            WXMediaMessage* msg=[WXMediaMessage message];
                            WXImageObject* obj=[WXImageObject object];
                            obj.imageData=data;
                            msg.mediaObject=obj;
                            SendMessageToWXReq* req=[[SendMessageToWXReq alloc]init];
                            req.bText=NO;
                            req.message=msg;
                            if(intFlag==0){
                                //分享到微信
                                req.scene=WXSceneSession;
                            }else if(intFlag==1){
                                //分享到微信朋友圈
                                req.scene=WXSceneTimeline;
                            }
                            [WXApi sendReq:req];
                        }
                    }];
                }
            }
        }else{
            NSString* tmp=[body getStr:@"haibao"];
            NSDictionary* haibao=[self dictionaryWithJsonString:tmp];
            [self sendWXMiniProgram:haibao];
        }
    }else if([message.name isEqualToString:@"copy"]){
        [StringUtil copyTxt:[body getStr:@"copyValue"]];
        [ViewUtils showToast:@"复制成功"];
        
    }else if([message.name isEqualToString:@"savePic"]){
        NSString* pic=[body getStr:@"picurl"];
        NSArray* imgs=[NSArray arrayWithObject:pic];
        [UIImageHelper downloadThenUpdateUI:imgs complete:^(NSArray *datas) {
            if(datas&&datas.count>0){
                UIImage* image=datas[0];
                [UIImageHelper saveImage:image completionHandler:^(BOOL success, NSError * _Nullable error) {
                    if(success){
                        [ViewUtils showToast:@"保存图片成功!"];
                    }else{
                        [ViewUtils showToast:@"保存图片失败!"];
                    }
                }];
            }
        }];
        
        
    }else if([message.name isEqualToString:@"shareInvite"]){
        [self dismissDialog];
        NSString* haibao=[body getStr:@"picurl"];
        int intFlag=[body getInt:@"flag"];
        if(intFlag==0||intFlag==1){
            if(![WXApi isWXAppInstalled]){
                [ViewUtils showToast:@"还没有安装微信哦～"];
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:weixin]];
                return;
            }
        }
        [WXApi registerApp:APP_ID];
        if(!haibao)return;
        NSArray* imgs=[NSArray arrayWithObject:haibao];
        [self showDialog:@"正在准备分享，请稍后"];
        [UIImageHelper downloadDataThenUpdateUI:imgs complete:^(NSArray *datas) {
            if(datas&&datas.count>0){
                NSData* data=datas[0];
                WXMediaMessage* msg=[WXMediaMessage message];
                WXImageObject* obj=[WXImageObject object];
                obj.imageData=data;
                msg.mediaObject=obj;
                SendMessageToWXReq* req=[[SendMessageToWXReq alloc]init];
                req.bText=NO;
                req.message=msg;
                if(intFlag==0){
                    //分享到微信
                    req.scene=WXSceneSession;
                }else if(intFlag==1){
                    //分享到微信朋友圈
                    req.scene=WXSceneTimeline;
                }
                [self dismissDialog];
                [WXApi sendReq:req];
            }
        }];
    }else if ([message.name isEqualToString:@"isInstalled"]) {
        
        BOOL isInstall = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:message.body[@"packageName"]]];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"packageName"] = message.body[@"packageName"];
        dict[@"installed"] = isInstall == YES ? @"true" : @"false";
        NSString *jsStr = [self convertJSONWithDic:dict];
        [self runJS:[NSString stringWithFormat:@"installed_receive('%@');",jsStr]];
        
    }else if ([message.name isEqualToString:@"setReminder"]) {
        //设置提醒事件
        NSString *tmp = message.body[@"text"];
        if (tmp) {
            // 先删除旧的提醒
            [CalendarReminderUtil removeEvent];
            NSString *title = body[@"title"];
            NSString *description = message.body[@"description"];
            NSDate *nowDate = [NSDate date];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy-MM-dd"];
            NSString *currentStr = [formatter stringFromDate:nowDate];
            NSDateFormatter *tempFormatter = [[NSDateFormatter alloc]init];
            [tempFormatter setDateStyle:NSDateFormatterMediumStyle];
            [tempFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
            NSDate *date = [tempFormatter dateFromString:[NSString stringWithFormat:@"%@ %@",currentStr,tmp]];
            long long reminderTime = [date timeIntervalSince1970];
            int previousMin = 5; // 提前5分钟提醒
            // 添加新的提醒
            [CalendarReminderUtil addEvent:title des:description time:reminderTime pre:previousMin];
        }else {
            [ViewUtils showToast:@"时间为空，无法设置提醒"];
        }
    }else if ([message.name isEqualToString:@"jump"]){
        if(![WXApi isWXAppInstalled]){
            [ViewUtils showToast:@"还没有安装微信哦～"];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:weixin]];
            return;
        }
        [WXApi registerApp:APP_ID];
        [self showDialog:@"正在跳转中..."];
        NSString * userName = [body getStr:@"userName"];
        NSString * path = [body getStr:@"path"];
        NSString * status = [body getStr:@"status"];
        if (userName != nil || path != nil || status != nil) {
            WXLaunchMiniProgramReq *req = [WXLaunchMiniProgramReq object];
            req.userName = userName;  //拉起的小程序的username 其实就是
            req.path = path;    //拉起小程序页面的可带参路径，不填默认拉起小程序首页
            if([status integerValue]==1){
                //正式版小程序
                req.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
            }else{
                //体验版小程序
                req.miniProgramType = WXMiniProgramTypePreview;
            }
            
            [WXApi sendReq:req];
        }
    }else if ([message.name isEqualToString:@"jumpAuth"]){
        if(![WXApi isWXAppInstalled]){
            [ViewUtils showToast:@"还没有安装微信哦～"];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:weixin]];
            return;
        }
        [WXApi registerApp:APP_ID];
        [self showDialog:@"正在跳转中..."];
        NSString* uid=[AppContext sharedContext].curUid;
        NSMutableDictionary* dict=[NSMutableDictionary dictionary];
        [dict putStr:uid key:@"uid"];
        __weak __typeof(self)weakSelf=self;
        [[ApiClient sharedApi] jumpAuth:dict cb:^(NSDictionary *data, NSError *connectionError) {
            [weakSelf dismissDialog];
            if(data){
                int r=[data getInt:@"r"];
                if(r==0){
                    NSDictionary* dictResult=[data getDict:@"result"];
                    NSString* ghid=[dictResult getStr:@"ghid"];
                    NSString* path=[dictResult getStr:@"path"];
                    int status=[dictResult getInt:@"status"];
                    
                    WXLaunchMiniProgramReq *req = [WXLaunchMiniProgramReq object];
                    req.userName = ghid;  //拉起的小程序的username 其实就是
                    req.path = path;    //拉起小程序页面的可带参路径，不填默认拉起小程序首页
                    if(status==1){
                        //正式版小程序
                        req.miniProgramType = WXMiniProgramTypeRelease;
                        //拉起小程序的类型
                    }else{
                        //体验版小程序
                        req.miniProgramType = WXMiniProgramTypePreview;
                    }
                    
                    [WXApi sendReq:req];
                    
                }else if(r==-1){
                    
                }
            }
        }];
        
    }else if ([message.name isEqualToString:@"awaken"]){
        NSString * uid_1 = [body getStr:@"uid"];
        NSString * weappid_2 = [body getStr:@"weappid"];
        NSString * page_1 = [body getStr:@"page"];
        NSString * page_pre_1 = [body getStr:@"page_pre"];
        NSString * packageName_1 = [body getStr:@"packageName"];
        NSString * app_url_1 = [body getStr:@"app_url"];
        if (uid_1 != nil && weappid_2 != nil && page_1 != nil && page_pre_1 != nil && packageName_1 != nil && app_url_1 != nil) {
            if (packageName_1 != nil) {
                NSString * str_3 = [NSString stringWithFormat:@"%s,%@,%s,%@,%s","installed(",uid_1,", ",weappid_2, ")"];
                [self postRunJS:str_3];
                NSString * str_4 = [NSString stringWithFormat:@"%s,%@,%s","loadAwaken('",page_1,"')"];
                [self postRunJS:str_4];
            }else{
                [ViewUtils showToast:@"请先安装应用~"];
                NSString * str_5 =[NSString stringWithFormat:@"%s,%@,%s,%@,%s","uninstalled(",uid_1, ", ",weappid_2,")"];
                [self postRunJS:str_5];
                //                self.webView
                NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:app_url_1]];
                [self.webView loadRequest:request];
            }
        }
        
    }else if ([message.name isEqualToString:@"share"]){
        if(![WXApi isWXAppInstalled]){
            [ViewUtils showToast:@"还没有安装微信哦～"];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:weixin]];
            return;
        }
        [WXApi registerApp:APP_ID_ARTICLE];
        [self dismissDialog];
        [self showDialog:@"正在分享中..."];
        NSString* uid=[AppContext sharedContext].curUid;
        NSString * type = [body getStr:@"type"];
        NSString * ua = @"ios";
        NSMutableDictionary * dict = [NSMutableDictionary dictionary];
        [dict putStr:uid key:@"uid"];
        [dict putStr:[body getStr:@"aid"] key:@"aid"];
        [dict putStr:type key:@"type"];
        [dict putStr:ua key:@"ua"];
        __weak __typeof(self)weakSelf=self;
        [[ApiClient sharedApi]share:dict cb:^(NSDictionary *data, NSError *connectionError) {
            [weakSelf dismissDialog];
            if(data){
                int r=[data getInt:@"r"];
                if(r==0){
                    NSDictionary* dictResult=[data getDict:@"list"];
                    NSString * URL = [dictResult getStr:@"url"];
                    NSURL * url = [NSURL URLWithString:URL];
                    NSString * title = [dictResult getStr:@"title"];
                    NSURL * urlPic = [NSURL URLWithString:[dictResult getStr:@"pic"]];
                    
                    NSData * imageData = [NSData dataWithContentsOfURL:urlPic];
                    UIImage * resultImage = [UIImage imageWithData:imageData];
                    UIImage * picImage = [self compressImage:resultImage toByte:32765];
                    
                    int stype = [data getInt:@"stype"];
                    if (stype == 1) { // 使用iOS原生分享
                        [ShareHelper shareArticle:title image:picImage url:url type:@"wchat" vc:self okfunc:^{
                            //分享完成
                        }];
                    } else { // 使用微信sdk分享
                        WXWebpageObject *webpageObject = [WXWebpageObject object];
                        webpageObject.webpageUrl = URL;
                        
                        WXMediaMessage *message = [WXMediaMessage message];
                        message.title = title;
                        message.description = title;
                        [message setThumbImage:picImage];
                        message.mediaObject = webpageObject;
                        
                        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
                        req.bText = NO;
                        req.message = message;
                        if ([type isEqualToString:@"weixin"]) {
                            req.scene = WXSceneSession;
                        }else{
                            req.scene = WXSceneTimeline;
                        }
                        [WXApi sendReq:req];
                    }
                }else if(r==-1){
                    
                }
            }
        }];
    }else if ([message.name isEqualToString:@"checkInstall"]){
        NSString * weappid_1 = [body getStr:@"weappid"];
        NSString * ispackName = [body getStr:@"packageName"];
        //判断bundle ID是否为空
        [self isInstallLDApp:[NSArray arrayWithObject:ispackName]];
        if (ispackName != nil) {
            //                NSString * string = [NSString stringWithFormat:@"%@",(installShow(" + weappid_1 + "))];
            NSString * string = [NSString stringWithFormat:@"%s,%@,%s","installShow(",weappid_1,")"];
            [self postRunJS:string];
            NSString * str_1 = [NSString stringWithFormat:@"%s,%@,%s","loadAwaken(", ispackName,")"];
            [self postRunJS:str_1];
        }else{
            NSString * str_2 = [NSString stringWithFormat:@"%s,%@,%s","unInstallHide(",weappid_1,")"];
            [self postRunJS:str_2];
        }
    }else if ([message.name isEqualToString:@"update"]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:body[@"path"]]];
        
    }else if ([message.name isEqualToString:@"pay"]){
        if(![WXApi isWXAppInstalled]){
            [ViewUtils showToast:@"还没有安装微信哦～"];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:weixin]];
            return;
        }
        NSString * pay = [body getStr:@"count"];
        if (pay != nil || [pay integerValue] > 0) {
            [self showDialog:@"正在跳转支付中..."];
            NSString* uid=[AppContext sharedContext].curUid;
            NSMutableDictionary* dict=[NSMutableDictionary dictionary];
            [dict putStr:uid key:@"uid"];
            [dict putStr:pay key:@"count"];
            __weak __typeof(self)weakSelf=self;
            [[ApiClient sharedApi]pay:dict cb:^(NSDictionary *data, NSError *connectionError) {
                [weakSelf dismissDialog];
                if(data){
                    int r=[data getInt:@"r"];
                    if(r==0){
                        NSDictionary* dictResult=[data getDict:@"result"];
                        NSString* ghid=[dictResult getStr:@"ghid"];
                        NSString* path=[dictResult getStr:@"path"];
                        int status=[dictResult getInt:@"status"];
                        
                        WXLaunchMiniProgramReq *req = [WXLaunchMiniProgramReq object];
                        req.userName = ghid;  //拉起的小程序的username 其实就是
                        req.path = path;    //拉起小程序页面的可带参路径，不填默认拉起小程序首页
                        if(status==1){
                            //正式版小程序
                            req.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
                        }else{
                            //体验版小程序
                            req.miniProgramType = WXMiniProgramTypePreview;
                        }
                        [WXApi sendReq:req];
                        
                    }else if(r==-1){
                        
                    }
                }
            }];
        }
        
    }else if ([message.name isEqualToString:@"imei"]) {
        
    }else if ([message.name isEqualToString:@"yyz"]) {
        NSString *urlStr = body[@"url"];
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlStr]]) {
           [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
        }
    }else if ([message.name isEqualToString:@"showShare"]) {
        
        NSDictionary* dictResult=[self dictionaryWithJsonString:[body getStr:@"shareInfo"]];
        NSString * URL = [dictResult getStr:@"curl1"];
//        NSURL * url = [NSURL URLWithString:URL];
        NSString * title = [dictResult getStr:@"title"];
        NSString *des = [dictResult getStr:@"des"];
        NSURL * urlPic = [NSURL URLWithString:[dictResult getStr:@"pic"]];
        
        NSData * imageData = [NSData dataWithContentsOfURL:urlPic];
        UIImage * resultImage = [UIImage imageWithData:imageData];
        UIImage * picImage = [self compressImage:resultImage toByte:32765];

        [self.view addSubview:self.shareButton];
        [WXApi registerApp:APP_ID_ARTICLE];
        __weak typeof(self) weakSelf = self;
        [self.shareButton addTapBlock:^(UIButton * _Nonnull btn) {
            if (weakSelf.urlScheme!=nil) {
                NSURL *url = [NSURL URLWithString:[weakSelf.urlScheme stringByAppendingString:URL]];
                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                    [[UIApplication sharedApplication] openURL:url];
                }
            }else {
                [StringUtil copyTxt:title];
                [ViewUtils show1Alert:nil content:@"分享文案已经复制到粘贴板，请在微信粘贴文章" ok:@"我知道了" action:^{
                    [ViewUtils showOneBtnImageName:@"share_weixn" OneBtnTitle:@"分享到微信" TwoBtnImageName:@"share_circle" TwoBtnTitle:@"分享到朋友圈" action:^(NSInteger index) {
                        WXWebpageObject *webpageObject = [WXWebpageObject object];
                        webpageObject.webpageUrl = URL;
                        
                        WXMediaMessage *message = [WXMediaMessage message];
                        message.title = title;
                        message.description = des;
                        [message setThumbImage:picImage];
                        message.mediaObject = webpageObject;
                        
                        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
                        req.bText = NO;
                        req.message = message;
                        if (index==1) {
                            req.scene = WXSceneSession;
                        }else{
                            req.scene = WXSceneTimeline;
                        }
                        [WXApi sendReq:req];
                    }];
                }];
            }
        }];
        
    }else if ([message.name isEqualToString:@"yyzplay"]) {
        NSString *urlStr = body[@"action"];
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlStr]]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
        }
        
    }else if ([message.name isEqualToString:@"loadTTAd"]){
        BURewardedVideoModel *model = [[BURewardedVideoModel alloc] init];
        model.userId = [AppContext sharedContext].curUid;
        model.rewardName = body[@"rewardName"];
        model.rewardAmount = [body[@"rewardAmount"] integerValue];
        model.extra = body[@"aid"];
        self.rewardedVideoAd = [[BURewardedVideoAd alloc] initWithSlotID:kRewardedID rewardedVideoModel:model];
        self.rewardedVideoAd.delegate = self;
        [self.rewardedVideoAd loadAdData];
        
    }else if ([message.name isEqualToString:@"playTTAd"]) {
        if (self.rewardedVideoAd!=nil) {
          [self.rewardedVideoAd showAdFromRootViewController:self.navigationController];
        }
    }else if ([message.name isEqualToString:@"loadSigmobAd"]) {
        WindAdRequest *request = [WindAdRequest request];
        request.userId = [AppContext sharedContext].curUid;
        request.options = nil;//如无需求可以为nil
        [[WindRewardedVideoAd sharedInstance] setDelegate:self];
        [[WindRewardedVideoAd sharedInstance] loadRequest:request withPlacementId:kSigmobRewardedID];
        
    }else if ([message.name isEqualToString:@"playSigmobAd"]){
        BOOL isReady = [[WindRewardedVideoAd sharedInstance] isReady:kSigmobRewardedID];
        if (isReady) {
            [[WindRewardedVideoAd sharedInstance] playAd:self withPlacementId:kSigmobRewardedID options:nil error:nil];
        }
    }
    /************************************************/
    if ([message.name isEqualToString:@"ttlqb_getClient_no"]) {
        NSString *idfa = [AppConfig getAppIDFA];
        NSMutableDictionary *responsDic = [NSMutableDictionary dictionary];
        responsDic[@"no"] = idfa;
        responsDic[@"client_no"] = [AppContext sharedContext].clientId;
        responsDic[@"state"] = @"1";
        NSString *jsonStr = [self convertJSONWithDic:responsDic];
        [self runJS:[NSString stringWithFormat:@"ttlqb_getClient_no_receive('%@');",jsonStr]];
        
    }else if ([message.name isEqualToString:@"ttlqb_getLoadUserInfo"]) {
        JKEncrypt * en = [[JKEncrypt alloc]init];
        NSString *idfa = [AppConfig getAppIDFA];
        NSString *app_Version = [AppConfig getAppVersion];
        NSString *idfv = [AppConfig getAppIDFV];
        NSString *bundleid = [AppConfig getAppBundleId];
        NSString *status = [AppConfig getNetWorkStates];
        NSString *imsi = [AppConfig getIMSI];
        NSString *model = [AppConfig getDeviceModel];
        NSString *device_Version = [AppConfig getDeviceVersion];
        NSString *janlbreak = [AppConfig isJailBreak];
        NSMutableDictionary *tep = [NSMutableDictionary dictionary];
        [tep putStr:[en Base64AfterEncryptStr:[body getStr:@"udid"]] key:@"fsd"];
        [tep putStr:[en DES3EncryptStr:idfa] key:@"ukd"];
        //iPhone_&iPhone9,1_&IOS_&11.4.1
        //设备+设备型号+IOS+系统版本号
        NSString *dtt = [NSString stringWithFormat:@"iPhone_&%@_&IOS_&%@",model,device_Version];
        [tep putStr:[en Base64AfterEncryptStr:dtt] key:@"dtt"];
        [tep putStr:[en DES3EncryptStr:app_Version] key:@"sr"];
        [tep putStr:[en DES3EncryptStr:janlbreak] key:@"ss"];
        [tep putStr:[en DES3EncryptStr:imsi] key:@"kk1"];
        [tep putStr:[en DES3EncryptStr:@""] key:@"dr1"];
        [tep putStr:[en DES3EncryptStr:status] key:@"ur"];
        [tep putStr:[en DES3EncryptStr:idfv] key:@"crm"];
        [tep putStr:[en DES3EncryptStr:bundleid] key:@"dot"];
        [tep putStr:[en Base64AfterEncryptStr:@""] key:@"cor"];
        [tep putStr:[en DES3EncryptStr:@""] key:@"gte"];
        [tep putStr:[en DES3EncryptStr:@""] key:@"qx9"];
        [tep putStr:[en DES3EncryptStr:@""] key:@"sid"];
        [tep putStr:[en DES3EncryptStr:@""] key:@"bsid"];
        [tep putStr:[en DES3EncryptStr:@""] key:@"ph"];
        [tep putStr:[en DES3EncryptStr:@""] key:@"co"];
        [tep putStr:[en DES3EncryptStr:@""] key:@"uks"];
        NSString *jsonStr = [self convertJSONWithDic:tep];
        [self runJS:[NSString stringWithFormat:@"ttlqb_getLoadUserInfo_receive('%@');",jsonStr]];
        
    }else if ([message.name isEqualToString:@"ttlqb_getOnlineStatus"]) {
        NSMutableDictionary *responsDic = [NSMutableDictionary dictionary];
        responsDic[@"state"] = [AppContext sharedContext].isStatus;
        NSString *jsonStr = [self convertJSONWithDic:responsDic];
        [self runJS:[NSString stringWithFormat:@"ttlqb_getOnlineStatus_receive('%@');",jsonStr]];
        
    }else if ([message.name isEqualToString:@"ttlqb_getBreakStatus"]) {
        NSMutableDictionary *responsDic = [NSMutableDictionary dictionary];
        responsDic[@"state"] = @"1";
        responsDic[@"isBreak"] = [AppConfig isJailBreak];
        NSString *jsonStr = [self convertJSONWithDic:responsDic];
        [self runJS:[NSString stringWithFormat:@"ttlqb_getBreakStatus_receive('%@');",jsonStr]];
        
    }else if ([message.name isEqualToString:@"ttlqb_pasteAction"]) {
        NSMutableDictionary *responsDic = [NSMutableDictionary dictionary];
        responsDic[@"state"] = @"1";
        responsDic[@"udid"]=[AppContext sharedContext].udid;
        responsDic[@"uid"]=[AppContext sharedContext].uid;
        responsDic[@"taskid"]=[body getStr:@"taskid"];
        responsDic[@"keyword"]=[body getStr:@"key"];
        NSString *jsonStr = [self convertJSONWithDic:responsDic];
        [self runJS:[NSString stringWithFormat:@"ttlqb_pasteAction_receive('%@');",jsonStr]];
        
    }else if ([message.name isEqualToString:@"ttlqb_getReInstallStatus"]) {
        BOOL isInstall = [AppConfig  checkAppIsInstalled:[body getStr:@"bundleid"]];
        NSMutableDictionary *responsDic = [NSMutableDictionary dictionary];
        responsDic[@"state"] = isInstall?@"1":@"0";
        NSString *jsonStr = [self convertJSONWithDic:responsDic];
        [self runJS:[NSString stringWithFormat:@"ttlqb_getReInstallStatus_receive('%@');",jsonStr]];
        
    }else if ([message.name isEqualToString:@"ttlqb_openApp"]) {
        BOOL isOpen = [AppConfig  openAppWithBundleID:[body getStr:@"bundleid"]];
        NSMutableDictionary *responsDic = [NSMutableDictionary dictionary];
        responsDic[@"state"]=@"1";
        responsDic[@"isOpen"]=isOpen?@"1":@"0";
        responsDic[@"udid"]=[AppContext sharedContext].udid;
        responsDic[@"uid"]=[AppContext sharedContext].uid;
        responsDic[@"taskid"]=[body getStr:@"taskid"];
        NSString *jsonStr = [self convertJSONWithDic:responsDic];
        [self runJS:[NSString stringWithFormat:@"ttlqb_openApp_receive('%@');",jsonStr]];
        
    }else if ([message.name isEqualToString:@"ttlqb_getInstallStatus"]) {
        BOOL isInstall = [AppConfig checkAppIsInstalled:[body getStr:@"bundleid"]];
        NSMutableDictionary *responsDic = [NSMutableDictionary dictionary];
        responsDic[@"state"] = isInstall?@"1":@"0";
        NSString *jsonStr = [self convertJSONWithDic:responsDic];
        [self runJS:[NSString stringWithFormat:@"ttlqb_getInstallStatus_receive('%@');",jsonStr]];
    }
}

//加载视频广告材料失败时调用此方法
- (void)rewardedVideoAd:(BURewardedVideoAd *)rewardedVideoAd didFailWithError:(NSError *)error
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"onAdError"] = @"true";
    dict[@"code"] = @(error.code);
    dict[@"message"] = error.localizedDescription;
    NSString *jsonStr = [self convertJSONWithDic:dict];
    [self runJS:[NSString stringWithFormat:@"ttad_reward_receive('%@');",jsonStr]];
}

//成功缓存
- (void)rewardedVideoAdVideoDidLoad:(BURewardedVideoAd *)rewardedVideoAd {
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"onRewardVideoCached"] = @"true";
    NSString *jsonStr = [self convertJSONWithDic:dict];
    [self runJS:[NSString stringWithFormat:@"ttad_reward_receive('%@');",jsonStr]];
}

//此方法在成功加载视频广告材料时调用
- (void)rewardedVideoAdDidLoad:(BURewardedVideoAd *)rewardedVideoAd
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"onRewardVideoAdLoad"] = @"true";
    NSString *jsonStr = [self convertJSONWithDic:dict];
    [self runJS:[NSString stringWithFormat:@"ttad_reward_receive('%@');",jsonStr]];
}

//广告显示
- (void)rewardedVideoAdDidVisible:(BURewardedVideoAd *)rewardedVideoAd {
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"onAdShow"] = @"true";
    NSString *jsonStr = [self convertJSONWithDic:dict];
    [self runJS:[NSString stringWithFormat:@"ttad_reward_receive('%@');",jsonStr]];
}

//单击视频广告时调用此方法
- (void)rewardedVideoAdDidClick:(BURewardedVideoAd *)rewardedVideoAd
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"onAdVideoBarClick"] = @"true";
    NSString *jsonStr = [self convertJSONWithDic:dict];
    [self runJS:[NSString stringWithFormat:@"ttad_reward_receive('%@');",jsonStr]];
}

//广告关闭
- (void)rewardedVideoAdDidClose:(BURewardedVideoAd *)rewardedVideoAd {
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"onAdClose"] = @"true";
    NSString *jsonStr = [self convertJSONWithDic:dict];
    [self runJS:[NSString stringWithFormat:@"ttad_reward_receive('%@');",jsonStr]];
}

//此方法在视频广告播放完成或发生错误时调用
- (void)rewardedVideoAdDidPlayFinish:(BURewardedVideoAd *)rewardedVideoAd didFailWithError:(NSError *)error {
    
    if (!error) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"onVideoComplete"] = @"true";
        NSString *jsonStr = [self convertJSONWithDic:dict];
        [self runJS:[NSString stringWithFormat:@"ttad_reward_receive('%@');",jsonStr]];
    
    }else {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"onVideoError"] = @"true";
        NSString *jsonStr = [self convertJSONWithDic:dict];
        [self runJS:[NSString stringWithFormat:@"ttad_reward_receive('%@');",jsonStr]];
    }
}

//服务器验证成功
- (void)rewardedVideoAdServerRewardDidSucceed:(BURewardedVideoAd *)rewardedVideoAd verify:(BOOL)verify {
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"onRewardVerify"] = @"true";
    dict[@"rewardVerify"] = verify?@"true":@"false";
    dict[@"rewardAmount"] = @(rewardedVideoAd.rewardedVideoModel.rewardAmount);
    dict[@"rewardName"] = rewardedVideoAd.rewardedVideoModel.rewardName;
    NSString *jsonStr = [self convertJSONWithDic:dict];
    [self runJS:[NSString stringWithFormat:@"ttad_reward_receive('%@');",jsonStr]];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"user_id"] = rewardedVideoAd.rewardedVideoModel.userId;
    param[@"reward_name"] = rewardedVideoAd.rewardedVideoModel.rewardName;
    param[@"reward_amount"] = @(rewardedVideoAd.rewardedVideoModel.rewardAmount);
    param[@"extra"] = rewardedVideoAd.rewardedVideoModel.extra;
    
    [[ApiClient sharedApi] postRewardParameters:param cb:^(NSDictionary *data, NSError *connectionError) {
        if (!connectionError) {
            NSLog(@"服务器验证成功=%@",data);
        }
    }];
}

#pragma mark - RewardVideoAd
//加载成功
-(void)onVideoAdLoadSuccess:(NSString * _Nullable)placementId {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"onVideoAdLoadSuccess"] = @"true";
    param[@"message"] = placementId;
    NSString *jsonStr = [self convertJSONWithDic:param];
    [self runJS:[NSString stringWithFormat:@"sigmobvedioad_receive('%@');",jsonStr]];
}

//开始播放
-(void)onVideoAdPlayStart:(NSString * _Nullable)placementId {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"onVideoAdPlayStart"] = @"true";
    param[@"message"] = placementId;
    NSString *jsonStr = [self convertJSONWithDic:param];
    [self runJS:[NSString stringWithFormat:@"sigmobvedioad_receive('%@');",jsonStr]];
}

//点击
-(void)onVideoAdClicked:(NSString * _Nullable)placementId {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"onVideoAdClicked"] = @"true";
    param[@"message"] = placementId;
    NSString *jsonStr = [self convertJSONWithDic:param];
    [self runJS:[NSString stringWithFormat:@"sigmobvedioad_receive('%@');",jsonStr]];
}

//完成（奖励）广告关闭
- (void)onVideoAdClosedWithInfo:(WindRewardInfo *)info placementId:(NSString *)placementId {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"onVideoAdClosed"] = @"true";
    param[@"message"] = placementId;
    NSString *jsonStr = [self convertJSONWithDic:param];
    [self runJS:[NSString stringWithFormat:@"sigmobvedioad_receive('%@');",jsonStr]];
}

//错误
-(void)onVideoError:(NSError *)error placementId:(NSString * _Nullable)placementId {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"onVideoAdLoadError"] = @"true";
    param[@"message"] = placementId;
    NSString *jsonStr = [self convertJSONWithDic:param];
    [self runJS:[NSString stringWithFormat:@"sigmobvedioad_receive('%@');",jsonStr]];
}

//播放完成
- (void)onVideoAdPlayEnd:(NSString *)placementId {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"onVideoAdPlayEnd"] = @"true";
    param[@"message"] = placementId;
    NSString *jsonStr = [self convertJSONWithDic:param];
    [self runJS:[NSString stringWithFormat:@"sigmobvedioad_receive('%@');",jsonStr]];
}

//播放出错
- (void)onVideoAdPlayError:(NSError *)error placementId:(NSString *)placementId {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"onVideoAdPlayError"] = @"true";
    param[@"message"] = placementId;
    NSString *jsonStr = [self convertJSONWithDic:param];
    [self runJS:[NSString stringWithFormat:@"sigmobvedioad_receive('%@');",jsonStr]];
}


//ad server 返回广告信息
- (void)onVideoAdServerDidSuccess:(NSString *)placementId {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"onVideoAdPreLoadSuccess"] = @"true";
    param[@"message"] = placementId;
    NSString *jsonStr = [self convertJSONWithDic:param];
    [self runJS:[NSString stringWithFormat:@"sigmobvedioad_receive('%@');",jsonStr]];
}

//ad server 无广告信息返回
- (void)onVideoAdServerDidFail:(NSString *)placementId {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"onVideoAdPreLoadFail"] = @"true";
    param[@"message"] = placementId;
    NSString *jsonStr = [self convertJSONWithDic:param];
    [self runJS:[NSString stringWithFormat:@"sigmobvedioad_receive('%@');",jsonStr]];
}


- (UIButton *)shareButton {
    
    if (!_shareButton) {
        _shareButton = [[TTButton alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-40-kSafeAreaBottom, self.view.frame.size.width, 40)];
        _shareButton.backgroundColor = [UIColor colorWithRed:234/255.0 green:130/255.0 blue:50/255.0 alpha:1];
        [_shareButton setTitle:@"分享文章" forState:UIControlStateNormal];
        [_shareButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }
    
    return _shareButton;
}

/**
 *  此方法会接受 JS 的alert
 *  但是 JS 的alert 不会在客户端弹出，会接受到 弹窗要弹出的数据 然后可以打印出来
 *  OC 调用 JS
 */
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler  {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark---检查是否安装了某个应用
-(void)isInstallLDApp:(NSArray *)allAPP{
    NSInteger zlConnt = 0;
    for(NSString * appStr in allAPP) {
        NSString *app = [NSString stringWithFormat:@"%@",appStr];//转换成字符串
        NSRange range = [app rangeOfString:@"LdWBrowserIPhone"];//是否包含这个bundle ID
        if (range.length > 1)
        {
            zlConnt ++;
        }
        if (zlConnt >= 1) {
            
        }else{
            
        }
    }
}

#pragma mark - 压缩图片
-(UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    // Compress by quality
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return image;
    
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) return resultImage;
    
    // Compress by size
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),(NSUInteger)(resultImage.size.height *sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    
    return resultImage;
}

#pragma WebView加载网页方法
-(void)postRunJS:(NSString*)strJS{
    NSString * URLStr = [NSString stringWithFormat:@"%s %@","javascript:",strJS];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    ;
    NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:URLStr]];
    [self.webView loadRequest:request];
    
}

-(void)runJS:(NSString*)str
{
    // oc调用js代码
    [self.webView evaluateJavaScript:str completionHandler:^(id _Nullable data, NSError * _Nullable error) {
        if (error) {
            NSLog(@"错误:%@", error.localizedDescription);
        }
    }];
}

//字典转JSON
-(NSString *)convertJSONWithDic:(NSDictionary *)dic {
    NSError *err;
    NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:kNilOptions error:&err];
    if (err) {
        return @"字典转JSON出错";
    }
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
    
//json转字典
-(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

-(NSArray *)arrayWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSArray *arr = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return arr;
}

-(void)sendWXMiniProgram:(NSDictionary*)params
{
    if(!params)return;
    NSString* img_card=[params getStr:@"img_card"];
    //先异步下载图片，完成后开始分享
    NSArray* imgs=[NSArray arrayWithObject:img_card];
    
    __weak __typeof(self)weakSelf=self;
    [UIImageHelper downloadThenUpdateUI:imgs complete:^(NSArray *datas) {
        [weakSelf dismissDialog];
        [WXApi registerApp:APP_ID];
        if(datas&&datas.count>0){
            UIImage* image=datas[0];
            NSString* ghid=[params getStr:@"ghid"];
            NSString* path=[params getStr:@"path"];
            NSString* title=[params getStr:@"title"];
            NSString* desc=[params getStr:@"desc"];
            int status=[params getInt:@"status"];
            WXMiniProgramObject* miniProgramObj=[[WXMiniProgramObject alloc] init];
            miniProgramObj.webpageUrl=@"http://www.qq.com";
            if(1==status){
                miniProgramObj.miniProgramType = WXMiniProgramTypeRelease; // 正式版
            }else{
                miniProgramObj.miniProgramType = WXMiniProgramTypePreview; // 体验版
            }
            miniProgramObj.userName=ghid;
            miniProgramObj.path=path;
            WXMediaMessage* msg=[WXMediaMessage message];
            msg.title=title;
            msg.description=desc;
            msg.mediaObject=miniProgramObj;
            [msg setThumbImage:image];
            
            SendMessageToWXReq* req=[[SendMessageToWXReq alloc] init];
            req.message=msg;
            //req.transaction = buildTransaction("webpage");
            req.scene=WXSceneSession;
            [WXApi sendReq:req];
        }
    }];
}

-(void)showDialog:(NSString*)msg
{
    [self.view showWaitingView:msg];
}

-(void)dismissDialog
{
    [self.view dismissWaitingView];
}

//在发送请求之前
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    //如果是跳转一个新页面
    if (navigationAction.targetFrame == nil) {
        [webView loadRequest:navigationAction.request];
    }
    decisionHandler(WKNavigationActionPolicyAllow);

}

//在收到响应后
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    
    decisionHandler(WKNavigationResponsePolicyAllow);
}

- (void)leftBack {
    
    if ([_webView canGoBack]) {
        [_webView goBack];
        [self.shareButton removeFromSuperview];
    }
}

//页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    [self.view showActivityViewAtCenter];
    
    NSString * urlStr = webView.URL.absoluteString;
    if ([urlStr hasPrefix:API_ROOT]) {
        self.navigationController.navigationBarHidden = YES;
    }else {
        self.navigationController.navigationBarHidden = NO;
        [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
        self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
        self.navigationItem.title = @"步步赚";
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBack)];
    }
    
    if ([urlStr containsString:@"/quiescent/login.html"] || [urlStr containsString:@"/quiescent/index/index.html"] || [urlStr containsString:URL_WEB]) {
        NSString *pastStr = [AppContext sharedContext].loadtag;
        NSArray *pastArray = [pastStr componentsSeparatedByString:@"_"];
        if ([pastStr isEqualToString:LOAD_TAG]) {
            //什么也不做
        }else if (pastArray.count==2) {
            [self runJS:[NSString stringWithFormat:@"window.localStorage.setItem('ios_clb', '%@');",pastStr]];
            [self runJS:[NSString stringWithFormat:@"window.localStorage.setItem('ch', '%@');",pastArray.lastObject]];
        }else if (pastArray.count==3) {
            [self runJS:[NSString stringWithFormat:@"window.localStorage.setItem('ios_clb', '%@');",pastStr]];
            [self runJS:[NSString stringWithFormat:@"window.localStorage.setItem('ch', '%@');",pastArray[1]]];
            [self runJS:[NSString stringWithFormat:@"window.localStorage.setItem('t_code', '%@');",pastArray[2]]];
        }
        
        NSString *curUid = [AppContext sharedContext].curUid;
        if (curUid!=nil) {
            [self runJS:[NSString stringWithFormat:@"window.localStorage.setItem('uid', '%@');",curUid]];
        }
        
        NSString *idfa = [AppConfig getAppIDFA];
        if (idfa!=nil) {
            [self runJS:[NSString stringWithFormat:@"window.localStorage.setItem('imei', '%@');",idfa]];
        }
    }

}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [self.view hideActivityViewAtCenter];
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitDiskImageCacheEnabled"];//自己添加的，原文没有提到。
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitOfflineWebApplicationCacheEnabled"];//自己添加的，原文没有提到。
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation
{
    [self.view hideActivityViewAtCenter];
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitDiskImageCacheEnabled"];//自己添加的，原文没有提到。
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitOfflineWebApplicationCacheEnabled"];//自己添加的，原文没有提到。
    [[NSUserDefaults standardUserDefaults] synchronize];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    //Dispose of any resources that can be recreated.
}


- (void)dealloc {
    //销毁/////////////
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"send_code"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"check_code"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"play"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"jumpReward"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"pauth"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"saveUid"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"showDialog"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"copy"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"savePic"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"shareInvite"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"shareToWx"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"isInstalled"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"setReminder"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"jump"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"jumpAuth"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"awaken"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"share"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"checkInstall"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"update"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"pay"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"imei"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"yyz"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"showShare"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"yyzplay"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"yyzplay"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"loadTTAd"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"playTTAd"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"loadSigmobAd"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"playSigmobAd"];
    /************************************************/
    [_webView.configuration.userContentController removeScriptMessageHandlerForName:@"ttlqb_getClient_no"];
    [_webView.configuration.userContentController removeScriptMessageHandlerForName:@"ttlqb_getLoadUserInfo"];
    [_webView.configuration.userContentController removeScriptMessageHandlerForName:@"ttlqb_getOnlineStatus"];
    [_webView.configuration.userContentController removeScriptMessageHandlerForName:@"ttlqb_getBreakStatus"];
    [_webView.configuration.userContentController removeScriptMessageHandlerForName:@"ttlqb_pasteAction"];
    [_webView.configuration.userContentController removeScriptMessageHandlerForName:@"ttlqb_getReInstallStatus"];
    [_webView.configuration.userContentController removeScriptMessageHandlerForName:@"ttlqb_openApp"];
    [_webView.configuration.userContentController removeScriptMessageHandlerForName:@"ttlqb_getInstallStatus"];
}

@end
